layui.use(['flow','form','layer','upload'],function(){
    var flow = layui.flow,
        form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        upload = layui.upload,
        $ = layui.jquery;

    form.on('select(pflag)', function(data){
        location.href='pictures?flag='+data.value;
    });
    form.on('select(pdate)', function(data){
        location.href='pictures?flag='+$("#flag").val()+'&id='+data.value;
    });

    //流加载图片
    var imgNums = 18;  //单页显示图片数量
    flow.load({
        elem: '#Images', //流加载容器
        done: function(page, next){ //加载下一页
            $.get("getPictures?flag="+flag+"&id="+id,function(res){
                //模拟插入
                var imgList = [],data = res.data;
                var maxPage = imgNums*page < data.length ? imgNums*page : data.length;
                setTimeout(function(){
                    for(var i=imgNums*(page-1); i<maxPage; i++){
                        imgList.push('<li pId="'+data[i].pId+'"><img layer-src="/images/picture/'+ data[i].pFilename +'" src="/images/picture/'+ data[i].pFilename +'" alt="'+data[i].alt+'"><div class="operate"><div class="check"><input type="checkbox" name="belle" lay-filter="choose" lay-skin="primary" title="'+data[i].alt+'"></div><i class="layui-icon img_del">&#xe640;</i></div></li>');
                    }
                    next(imgList.join(''), page < (data.length/imgNums));
                    form.render();

                    $("#Images li img").width('100%');
                    $("#Images li img").height($("#Images li img").width());
                    $("#Images li img").width('auto');
                }, 200);
            });
        }
    });

    //设置图片的高度
    $(window).resize(function(){
        $("#Images li img").width('100%');
        $("#Images li img").height($("#Images li img").width());
        $("#Images li img").width('auto');
    })

    //多图片上传
    upload.render({
        elem: '.uploadNewImg',
        url: '../../json/userface.json',
        multiple: true,
        before: function(obj){
            //预读本地文件示例，不支持ie8
            obj.preview(function(index, file, result){
                $('#Images').prepend('<li><img layer-src="'+ result +'" src="'+ result +'" alt="'+ file.name +'" class="layui-upload-img"><div class="operate"><div class="check"><input type="checkbox" name="belle" lay-filter="choose" lay-skin="primary" title="'+file.name+'"></div><i class="layui-icon img_del">&#xe640;</i></div></li>')
                //设置图片的高度
                $("#Images li img").height($("#Images li img").width());
                form.render("checkbox");
            });
        },
        done: function(res){
            //上传完毕
        }
    });

    //弹出层
    $("body").on("click","#Images img",function(){
        showImg($(this));
    })
    //图片管理弹窗
    window.showImg = function showImg(a){
        var src = a.attr("src");
        var x = a.height()/a.width();
        var height = window.screen.height,
            width = window.screen.width;
        var area = '800px';
        var body =  $(window);
        if ( body.height()<body.width()) {
            console.log(1);
            if (body.height()<=800) {
                area = body.height() * 0.9/x + 'px';
                console.log("1,"+body.height());
            }
        }
        else{
            console.log(2);
            if (body.width()<=800)
                area = body.width() * 0.9 + 'px';
        }
        console.log(body.width()+"----"+body.height()+"---area:"+area);
        // console.log(x+","+height);
        // if ($("body").height()*0.8<=800*x) {
        //     area = 'auto';
        //     console.log("auto");
        // }
        if (width<520) {
            area = '95%';
        }
        //图片预览
        top.layer.open({
            type: 1,
            title: false,
            closeBtn: 1,
            area: area,
            // maxWidth:width*0.95,
            // maxHeight:716,
            skin: 'layui-layer-nobg', //没有背景色
            shadeClose: true
            ,content: '<img src="'+src+'" width="100%" height="100%" style="">'
        });
    }

    //删除单张图片
    $("body").on("click",".img_del",function(){
        var _this = $(this);
        var ids = [];
        layer.confirm('确定删除图片"'+_this.siblings().find("input").attr("title")+'"吗？',{icon:3, title:'提示信息'},function(index){
            ids.push(parseInt(_this.parents("li").attr("pId")));
            $.ajax({
                url: "delPicture",
                dataType: "json",
                type: "post",
                data: {
                    ids: ids
                },
                success: function (data) {
                    if (data.status == 1) {
                        _this.parents("li").hide(1000);
                        setTimeout(function(){_this.parents("li").remove();},950);
                    }
                    else if (data.status == 0) {
                        layer.msg('删除失败', {
                            icon: 0
                            , time: 1000
                        });
                    }
                },
                error: function (result) {
                    console.log(result);
                    alert("系统繁忙！");
                }
            });
            layer.close(index);
        });
    })

    //全选
    form.on('checkbox(selectAll)', function(data){
        var child = $("#Images li input[type='checkbox']");
        child.each(function(index, item){
            item.checked = data.elem.checked;
        });
        form.render('checkbox');
    });

    //通过判断是否全部选中来确定全选按钮是否选中
    form.on("checkbox(choose)",function(data){
        var child = $(data.elem).parents('#Images').find('li input[type="checkbox"]');
        var childChecked = $(data.elem).parents('#Images').find('li input[type="checkbox"]:checked');
        if(childChecked.length == child.length){
            $(data.elem).parents('#Images').siblings("blockquote").find('input#selectAll').get(0).checked = true;
        }else{
            $(data.elem).parents('#Images').siblings("blockquote").find('input#selectAll').get(0).checked = false;
        }
        form.render('checkbox');
    })

    //批量删除
    $(".batchDel").click(function(){
        var $checkbox = $('#Images li input[type="checkbox"]');
        var $checked = $('#Images li input[type="checkbox"]:checked');
        var ids = [];
        if($checkbox.is(":checked")){
            layer.confirm('确定删除选中的图片？',{icon:3, title:'提示信息'},function(index){
                $checked.each(function(){
                    ids.push(parseInt($(this).parents("li").attr("pId")));
                })
                var index = layer.msg('删除中，请稍候',{icon: 16,time:false,shade:0.8});
                $.ajax({
                    url: "delPicture",
                    dataType: "json",
                    type: "post",
                    data: {
                        ids: ids
                    },
                    success: function (data) {
                        layer.close(index);
                        if (data.status == 1) {
                            //删除数据
                            $checked.each(function(){
                                $(this).parents("li").hide(1000);
                                setTimeout(function(){$(this).parents("li").remove();},950);
                            })
                            $('#Images li input[type="checkbox"],#selectAll').prop("checked",false);
                            form.render();
                            layer.msg("删除成功");
                        }
                        else if (data.status == 0) {
                            layer.msg('删除失败', {
                                icon: 0
                                , time: 1000
                            });
                        }
                    },
                    error: function (result) {
                        layer.close(index);
                        console.log(result);
                        alert("系统繁忙！");
                    }
                });
            })
        }else{
            layer.msg("请选择需要删除的图片");
        }
    })

})